<?php
declare(strict_types=1);
namespace Framework;
use App\Model;
use Framework\Support\MySqlDb;
use Framework\Support\RedisCache;
use Framework\Support\SqliteDb;
use Swoole\Timer;

class Process
{

	public function __construct(\Closure $closure,$num = 1)
	{

        for ($i=0;$i<$num;$i++){
            $p = new \Swoole\Process(function (\Swoole\Process $process) use($closure){
                try {
                    $_ENV['bizan']->http_server->worker_id=$process->id;
                    file_put_contents_try(__TMPDIR__.'pid/'.$process->id.'.pid', (string)$process->pid);

                    \Swoole\Timer::tick(1000, function ($id) use($process)  {//每一秒通知服务状态
                        $d = $_ENV['bizan']->http_server->stats();
                        $_ENV['Table']['WorkersStatus']->set($process->id."", ['Request' => $d['worker_request_count'], 'Task' => 2, 'Pid' => $process->pid, 'Time' => time()]);
                    });

                    $_ENV['db_ws'] = new SqliteDb(__TMPDIR__.'ws.db');
                    $_ENV['db_tb_one_task_key'] = new SqliteDb(__TMPDIR__.'tb_one_task_key.db');

                    (PHP_OS != 'Darwin' && !str_starts_with(PHP_OS, "CYGWIN")) && swoole_set_process_name("{$_ENV['bizan']->name} php {$_ENV['bizan']->start_file} process worker {$process->id}");
                    $_ENV['startmemory'] = getum();
                    $star_time = get_ut();

                    $_ENV['database'] = include __SERDIR__ . __LV__ . '_database.php';
                    $database = $_ENV['database'];
                    $include_model_files = glob(__SYSDIR__ . '*.php');
                    foreach ($include_model_files as $model_file) {
                        $name = str_replace([__SYSDIR__, '.php'], '', $model_file);
                        if($name!='Tables'){
                            $_ENV['sys'][$name] = require_once _include($model_file);
                        }
                    }

                    if ($database['CACHE']) {
                        foreach ($database['CACHE'] as $name => $row) {
                            $_ENV['cache_class'][$name] = new RedisCache($row,$name);
                        }
                    }

                    if ($database['DB']) {
                        foreach ($database['DB'] as $name => $row) {
                            $_ENV['db_class'][$name] = new MySqlDb($row,$name);
                        }
                    }
                    $_ENV['plugin_srcfiles'] = [];
                    $_ENV['plugin_paths'] = [];
                    $_ENV['plugins'] = [];// 跟官方插件合并
                    $_ENV['official_plugins'] = [];// 官方插件列表
                    $_ENV['g_include_slot_kv'] = [];// 官方插件列表

                    plugin_init();//插件初始化
                    plugin_get_hook();//获取启用的钩子
                    plugin_get_autoload();
                    plugin_get_model();
                    plugin_get_controller();

                    $_ENV['conf'] = include _include( __SERDIR__ . __LV__ . '_config.php');

                    $include_public_files = glob(__PUBDIR__ . '*.php');
                    foreach ($include_public_files as $public_file) {
                        require_once _include($public_file);
                    }

                    $is_load = [];
                       $_ENV['_models'] = [];
                       foreach ($_ENV['plugin_model_files'] as $k => $model_file) {
                           if (file_exists($model_file)) {
                               $is_load[$k] = $model_file;
                               //require_once _include($model_file);
                           }
                       }

                       $include_model_files = glob(__APPDIR__ . 'Model/*Model.php');
                       foreach ($include_model_files as $model_file) {
                           $name = str_replace([__APPDIR__ . "Model/", 'Model.php'], '', $model_file);
                           if (!isset($is_load[$name]) && file_exists($model_file)) {
                               $is_load[$name] = $model_file;
                               //require_once _include($model_file);
                           }
                       }

                       $include_model_files = glob(__APPDIR__ . 'Model/*/*Model.php');
                       foreach ($include_model_files as $model_file) {
                           $name = str_replace([dirname($model_file) . "/", 'Model.php'], '', $model_file);
                           if (!isset($is_load[$name]) && file_exists($model_file)) {
                               $is_load[$name] = $model_file;
                               //require_once _include($model_file);
                           }
                       }
                       $is_load_field = [];
                       $fields=[];
                       foreach ($_ENV['plugin_field_files'] as $k => $model_file) {
                           if (file_exists($model_file)) {
                               $is_load_field[$k] = 1;
                               require_once _include($model_file);
                               $fields[]=['label'=>$k,'id'=> constant("\\Field\\".$k.'Const::fields')];
                           }
                       }

                       $include_model_files = glob(__APPDIR__ . 'Field/*.php');
                       foreach ($include_model_files as $model_file) {
                           $name = str_replace([__APPDIR__ . "Field/", '.php'], '', $model_file);
                           if (!isset($is_load_field[$name]) && file_exists($model_file)) {
                               $is_load_field[$name] = 1;
                               require_once _include($model_file);
                               $fields[]=['label'=>$name,'id'=> constant("\\Field\\".$name.'Const::fields')];
                           }
                       }

                       $include_model_files = glob(__APPDIR__ . 'Field/*/*.php');
                       foreach ($include_model_files as $model_file) {
                           $name = str_replace([dirname($model_file) . "/", '.php'], '', $model_file);
                           if (!isset($is_load_field[$name]) && file_exists($model_file)) {
                               $is_load_field[$name] = 1;
                               require_once _include($model_file);
                               $fields[]=['label'=>$name,'id'=> constant("\\Field\\".$name.'Const::fields')];
                           }
                       }
                       $is_load_dao = [];
                       foreach ($_ENV['plugin_dao_files'] as $k => $model_file) {
                           if (file_exists($model_file)) {
                               $is_load_dao[$k] = $model_file;
                               //require_once _include($model_file);
                               $model = "\\Dao\\{$k}Dao";
                               $_ENV['_models_name'][$k] = $model;
                           }
                       }

                       $include_model_files = glob(__APPDIR__ . 'Dao/*Dao.php');
                       foreach ($include_model_files as $model_file) {
                           $name = str_replace([__APPDIR__ . "Dao/", 'Dao.php'], '', $model_file);
                           if (!isset($is_load_dao[$name]) && file_exists($model_file)) {
                               $is_load_dao[$name] = $model_file;
                               //require_once _include($model_file);
                               $model = "\\Dao\\{$name}Dao";
                               $_ENV['_models_name'][$name]=$model;
                           }
                       }

                       $include_model_files = glob(__APPDIR__ . 'Dao/*/*Dao.php');
                       foreach ($include_model_files as $model_file) {
                           $name = str_replace([dirname($model_file) . "/", 'Dao.php'], '', $model_file);
                           if (!isset($is_load_dao[$name]) && file_exists($model_file)) {
                               $is_load_dao[$name] = $model_file;
                               //require_once _include($model_file);
                               $model = "\\Dao\\{$name}Dao";
                               $_ENV['_models_name'][$name]=$model;
                           }
                       }

                       $libs = glob(__CFRDIR__ . 'Libs/*.php');
                       foreach ($libs as $_file) {
                           if ($_file == __CFRDIR__ . 'Libs/App.php') {
                               continue;
                           }
                           include_once _include($_file);
                       }

                       require_once _include(__APPDIR__ . 'Controller/Event.php');
                       require_once _include(__APPDIR__ . 'Model.php');

                       foreach ($is_load as $name){
                           require_once _include($name);
                       }

                       foreach ($is_load_dao as $name){
                           require_once _include($name);
                       }

                       $_ENV['_models']=[];
                       foreach ($_ENV['_models_name'] as $name => $model) {
                           $_ENV['_models'][$name] = new $model();
                       }
                       foreach ($_ENV['_models'] as $name => $model) {
                           $model->auto_load();
                       }

                    echo "Worker ID:" . str_pad((string)$process->id, 4) . ' Pid:' . str_pad((string)$process->pid, 8) ." Ut:".str_pad(ut($star_time),12)." Um:".str_pad(um($_ENV['startmemory']),12). ' Process' . "\r\n";

                    $models = new Model();
                    $closure($process,$models);

                }catch (\Throwable $e) {

                }
            },false,2,true);
            $_ENV['bizan']->http_server->addProcess($p);
        }
	}
}

?>